package com.reggie.module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.common.ResultResponseVo;
import com.reggie.common.enums.backend.EmployeeEnum;
import com.reggie.module.entity.dto.employeeDto.AddEmployeeDto;
import com.reggie.module.entity.dto.employeeDto.ChangeStatusDto;
import com.reggie.module.entity.dto.employeeDto.EmployeeLoginDto;
import com.reggie.module.entity.dto.employeeDto.UpdateEmployeeDto;
import com.reggie.module.entity.po.Employee;
import com.reggie.module.mapper.EmployeeMapper;
import com.reggie.module.service.EmployeeService;
import com.reggie.utils.JWTUtil;
import com.reggie.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;

import static com.reggie.common.Constant.LOGIN_SESSION;

/**
 * @Author 早睡蛋
 * @Date 2022/9/17 14:29:22
 * @Desc:
 */
@Service
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 登录
     *
     * @param request
     * @param employeeLoginDto
     * @return
     */
    @Override
    public ResultResponseVo login(HttpServletRequest request, EmployeeLoginDto employeeLoginDto) {
        Map<String, Object> map = new HashMap<>();
        String password = employeeLoginDto.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        String username = employeeLoginDto.getUsername();
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, username);
        Employee employee = employeeMapper.selectOne(queryWrapper);
        if (null == employee || !password.equals(employee.getPassword())) {
            return EmployeeEnum.LOGIN_FAIL.getResultResponseVo();
        }
        if (0 == employee.getStatus()) {
            return EmployeeEnum.EM_LOCKED.getResultResponseVo();
        }
        String empToken = JWTUtil.createEmpToken(employee);
        map.put("employee", employee);
        map.put("userToken", empToken);
        redisUtil.setStringExpire(LOGIN_SESSION + employee.getId(), empToken, (long) (60 * 60 * 24 * 7));
        return EmployeeEnum.LOGIN_OK.getResultResponseVo().setData(map);
    }

    /**
     * 退出
     *
     * @param request
     * @return
     */
    @Override
    public ResultResponseVo logout(HttpServletRequest request) {
        try {
            request.getSession().removeAttribute(LOGIN_SESSION);
            return EmployeeEnum.LOGOUT_OK.getResultResponseVo();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 添加员工
     *
     * @param request
     * @param addEmployeeDto
     * @return
     */
    @Override
    @Transactional
    public ResultResponseVo save(HttpServletRequest request, AddEmployeeDto addEmployeeDto) {
        Employee byUserName = employeeMapper.findByUserName(addEmployeeDto.getUsername());
        if (byUserName != null) {
            return EmployeeEnum.USERNAME_EXIST.getResultResponseVo();
        }
        Employee byPhone = employeeMapper.findByPhone(addEmployeeDto.getPhone());
        if (byPhone != null) {
            return EmployeeEnum.PHONE_EXIST.getResultResponseVo();
        }
        Employee byIdNumber = employeeMapper.findByIdNumber(addEmployeeDto.getIdNumber());
        if (byIdNumber != null) {
            return EmployeeEnum.IdNUMBER_EXIST.getResultResponseVo();
        }
        Employee employee = addEmployeeDto.addEmp(request);
        int insert = employeeMapper.insert(employee);
        if (insert > 0) {
            return EmployeeEnum.SAVE_OK.getResultResponseVo();
        }
        return EmployeeEnum.SAVE_FAIL.getResultResponseVo();
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public ResultResponseVo selectByPage(int page, int pageSize, String name) {
        Page<Employee> employeePage = new Page<>(page, pageSize, true);
        QueryWrapper<Employee> employeeQueryWrapper = new QueryWrapper<>();

        employeeQueryWrapper.select("id", "name", "username", "phone", "status");
        log.info("name = {}", name);
        if (StringUtils.isNotEmpty(name)) {
            employeeQueryWrapper.like("name", name);
        }
        IPage<Employee> employeeIPage = employeeMapper.selectPage(employeePage, employeeQueryWrapper);
        return EmployeeEnum.SUCCESS.getResult().setData(employeeIPage);
    }

    /**
     * 修改员工状态信息
     *
     * @param changeStatusDto
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResultResponseVo changeStatus(ChangeStatusDto changeStatusDto, HttpServletRequest request) {
        ChangeStatusDto result = new ChangeStatusDto(changeStatusDto.getId(), changeStatusDto.getStatus(), request);
        int i = employeeMapper.changeStatus(result);
        if (i > 0) {
            return EmployeeEnum.STATUS_CHANGE_OK.getResultResponseVo();
        }
        return EmployeeEnum.STATUS_CHANGE_FAIL.getResultResponseVo();
    }

    /**
     * 修改员工前获取员工信息
     *
     * @param id
     * @return
     */
    @Override
    public ResultResponseVo getByEmpId(Long id) {
        QueryWrapper<Employee> employeeQueryWrapper = new QueryWrapper<>();
        employeeQueryWrapper.select("*").eq("id", id);
        Employee employee = employeeMapper.selectOne(employeeQueryWrapper);
        return EmployeeEnum.SUCCESS.getResultResponseVo().setData(employee);
    }

    /**
     * 编辑员工信息
     *
     * @param updateEmployeeDto
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResultResponseVo updateEmp(UpdateEmployeeDto updateEmployeeDto, HttpServletRequest request) {
        long id1 = Thread.currentThread().getId();
        log.info("线程id为：{}", id1);
        Long id = updateEmployeeDto.getId();
        Employee byUserName = employeeMapper.findByUserName(updateEmployeeDto.getUsername());
        if (byUserName != null && !byUserName.getId().equals(id)) {
            return EmployeeEnum.USERNAME_EXIST.getResultResponseVo();
        }
        Employee byPhone = employeeMapper.findByPhone(updateEmployeeDto.getPhone());
        if (byPhone != null && !byPhone.getId().equals(id)) {
            return EmployeeEnum.PHONE_EXIST.getResultResponseVo();
        }
        Employee byIdNumber = employeeMapper.findByIdNumber(updateEmployeeDto.getIdNumber());
        if (byIdNumber != null && !byIdNumber.getId().equals(id)) {
            return EmployeeEnum.IdNUMBER_EXIST.getResultResponseVo();
        }
        Employee employee = updateEmployeeDto.updateEmp(request);
        int result = employeeMapper.updateEmp(employee);
        if (result > 0) {
            return EmployeeEnum.UPDATE_OK.getResultResponseVo();
        }
        return EmployeeEnum.UPDATE_FAIL.getResultResponseVo();
    }

}
